package com.gonsin.ta.logic.parse.operator;

import com.gonsin.ta.logic.exceptions.TaException;
import com.gonsin.ta.logic.parse.Chain;
import com.gonsin.ta.logic.parse.condition.Executable;
import com.gonsin.ta.logic.parse.condition.FutureCondition;
import com.gonsin.ta.logic.parse.condition.RunCondition;
import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.Operator;
import com.ql.util.express.instruction.op.OperatorBase;
import com.ql.util.express.instruction.opdata.OperateDataAttr;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 运行节点
 */
@Slf4j
public class RunOperator extends OperatorBase {

    private Chain chain;

    public RunOperator(Chain chain) {
        this.chain = chain;
    }

//    @Override
//    public Object executeInner(Object[] objects) throws Exception {
//    }

    @Override
    public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {

        if (list.length <= 0){
            throw new TaException("chain id = {}, RUN方法不能没有参数", chain.getChainId());
        }

        RunCondition condition = new RunCondition();
//        OperateData operateData = list.get(-1);
//        if(operateData instanceof OperateDataAttr){
//            condition.setName(((OperateDataAttr) operateData).getName());
//        }
//        condition.setName(list.get(0).getName());

//        boolean first = (boolean) parent.get("first");
//        if(first){
//            first = false;
//            parent.put("first", first);
//            condition.setRootCondition(true);
//        }

        for (int i = 0; i < list.length; i++){
            OperateData data = list.get(i);
            Object obj = data.getObject(parent);

            if (obj instanceof Executable){
                condition.addExecutable((Executable)obj);
            }else{
                OperateDataAttr attr = (OperateDataAttr)data;
                Object symbolGet = parent.getSymbol(attr.getName());
                if(symbolGet != null){
                    FutureCondition f = new FutureCondition();
                    f.setConditionName(attr.getName());
                    condition.addExecutable(f);
                } else {
                    throw new TaException("chain id = {}, RUN方法里找不到 【{}】", chain.getChainId(), attr.getName());
                }
                throw new TaException("chain id = {}, RUN方法的参数【{}】错误，因为不是Ta组件", chain.getChainId(), Objects.toString(attr.getName()));
            }
        }
//        condition.handleThis();
        OperateData data = new OperateData(condition, condition.getClass());

        return data;
    }
}
